<template>
  <div class="appointment">
    <ivue-crud
      :data="appointments"
      :dialogOpen.sync="dialogOpen"
      :editData="editData"
      :isUpdate="isUpdate"
      :option="option"
      :searchForm.sync="searchForm"
      :show-page="false"
      :syncDataReady="syncDataReady"
      :tableLoading="loading"
      :title="title"
      @on-create="onCreate"
      @on-page-change="pageChange"
      @on-page-size-change="pageSizeChange"
      @on-update="onUpdate"
      @search="doSearch"
      dialog-width="60%"
      ref="ivueCrud"
    >
      <div slot="headerMenu">
        <Button :size="option.searchSize" @click="historySearch" custom-icon="iconfont " type="warning">历史版本</Button>
        <Button :loading="loading" :size="option.searchSize" @click="doSearch" custom-icon="iconfont icon-shuaxin"
                type="primary">刷新
        </Button>
        <Button :size="option.searchSize" @click="create" custom-icon="iconfont icon-plus" type="success">新增</Button>
      </div>
    </ivue-crud>
  </div>
</template>

<script>
  import ajax from '../../../api/http'

  export default {
    name: 'appointment',
    data() {
      return {
        resource: 'appointment',
        type: 'Appointment',
        dialogOpen: false,
        editData: {},
        isUpdate: false,
        searchForm: {},
        syncDataReady: true,
        loading: false,
        title: '预约'
      }
    },
    computed: {
      appointments() {
        // this.$store.state.medication.medications
        let jData = []
        this.$store.state.medication.medications.forEach(entry => {
          let re = entry.resource
          if (re.total && re.total.myStringValue == '0') return
          jData.push({
            url: re.id.myStringValue,
            id: re.id.myUnqualifiedId,
            versionId: re.id.myUnqualifiedVersionId,
            status: re.status ? re.status.myStringValue : '',
            appointmentId: re.identifier && re.identifier.length && re.identifier[0].value ? re.identifier[0].value.myStringValue : '',
            patientId:
              re.participant && re.participant.length === 3 && re.participant[0].actor && re.participant[0].actor.reference
                ? re.participant[0].actor.reference.myStringValue.replace('Patient/','')
                : '',
            patientName:
              re.participant && re.participant.length === 3 && re.participant[0].actor && re.participant[0].actor.display
                ? re.participant[0].actor.display.myStringValue
                : '',
            visitDoctorName:
              re.participant && re.participant.length === 3 && re.participant[1].actor && re.participant[1].actor.display
                ? re.participant[1].actor.display.myStringValue
                : '',
            visitDeptName:
              re.participant && re.participant.length === 3 && re.participant[2].actor && re.participant[2].actor.display
                ? re.participant[2].actor.display.myStringValue
                : '',
            serviceTypeCode:
              re.serviceType && re.serviceType.length && re.serviceType[0].coding && re.serviceType[0].coding.length && re.serviceType[0].coding[0].code
                ? re.serviceType[0].coding[0].code.myStringValue
                : '',
            serviceTypeName:
              re.serviceType &&
              re.serviceType.length &&
              re.serviceType[0].coding &&
              re.serviceType[0].coding.length &&
              re.serviceType[0].coding[0].display
                ? re.serviceType[0].coding[0].display.myStringValue
                : '',
            appointmentTypeCode:
              re.appointmentType && re.appointmentType.coding && re.appointmentType.coding.length && re.appointmentType.coding[0].code
                ? re.appointmentType.coding[0].code.myStringValue
                : '',
            appointmentTypeName:
              re.appointmentType && re.appointmentType.coding && re.appointmentType.coding.length && re.appointmentType.coding[0].display
                ? re.appointmentType.coding[0].display.myStringValue
                : '',
            startTime: re.start && re.start.myStringValue ? this.formatDate(re.start.myStringValue, 'yyyy-mm-dd hh:mm:ss') : '',
            endTime: re.end && re.end.myStringValue ? this.formatDate(re.end.myStringValue, 'yyyy-mm-dd hh:mm:ss') : ''
          })
        })
        return jData
      },
      option() {
        return {
          resource: this.resource,
          searchSize: 'small',
          dialog: true,
          inline: true,
          searchForm: true,
          formGroup: true,
          border: true,
          column: [
            {
              label: '#',
              width: 50,
              type: 'index'
            },
            {
              label: 'ID',
              prop: 'id',
              search: true
            },
            {
              label: '预约ID',
              prop: 'appointmentId',
              editable: true,
              rules: [{required: true, message: '请输入预约ID', trigger: 'blur'}]
            },
            {
              label: '患者ID',
              prop: 'patientId',
              editable: true,
              hideInTb: true,
              rules: [{required: true, message: '请输入患者ID', trigger: 'blur'}]
            },
            {
              label: '姓名',
              prop: 'patientName',
              search: true,
              editable: true,
              rules: [{required: true, message: '请输入姓名', trigger: 'blur'}]
            },
            {
              label: '门诊类型',
              prop: 'serviceTypeCode',
              type: 'select',
              labelInValue: true,
              syncLabel: 'serviceTypeName',
              filterable: true,
              editable: true,
              dicData: [{label: '普通门诊', value: '397'}],
              rules: [{required: true, message: '请选择门诊类型', trigger: 'change'}],
              hideInTb: true
            },
            {
              label: '门诊类型',
              prop: 'serviceTypeName'
            },
            {
              label: '预约类型',
              prop: 'appointmentTypeCode',
              type: 'select',
              labelInValue: true,
              syncLabel: 'appointmentTypeName',
              filterable: true,
              editable: true,
              dicData: [{label: '复诊', value: '1'}],
              rules: [{required: true, message: '请选择预约类型', trigger: 'change'}],
              hideInTb: true
            },
            {
              label: '预约类型',
              prop: 'appointmentTypeName'
            },
            {
              label: '预约开始时间',
              prop: 'startTime',
              type: 'datetime',
              editable: true,
              rules: [{required: true, message: '请选择预约开始时间', trigger: 'change'}]
            },
            {
              label: '预约结束时间',
              prop: 'endTime',
              type: 'datetime',
              editable: true,
              rules: [{required: true, message: '请选择预约结束时间', trigger: 'change'}]
            },
            {
              label: '就诊医生',
              prop: 'visitDoctorName',
              editable: true,
              rules: [{required: true, message: '请输入就诊医生', trigger: 'blur'}]
            },
            {
              label: '就诊科室',
              prop: 'visitDeptName',
              editable: true,
              rules: [{required: true, message: '请输入就诊科室', trigger: 'blur'}]
            },
            {
              label: '操作',
              width: 100,
              type: 'render',
              render: (h, params) => {
                return h(
                  'div',
                  {
                    class: 'btn-wrap'
                  },
                  [
                    h(
                      'a',
                      {
                        on: {
                          click: () => {
                            this.update(params.row)
                          }
                        }
                      },
                      '编辑'
                    ),
                    h('Divider', {
                      props: {type: 'vertical'}
                    }),
                    h(
                      'a',
                      {
                        on: {
                          click: () => {
                            this.remove(params.row)
                          }
                        }
                      },
                      '删除'
                    )
                  ]
                )
              }
            }
          ]
        }
      }
    },
    created() {
      this.doSearch()
    },
    methods: {
      historySearch() {
        if (!this.searchForm.id) {
          this.$Message.error('请输入ID')
          return
        }
        this.loading = true
        this.$store
          .dispatch('getHistoryMedicationList', {
            type: this.type,
            id: this.searchForm.id
          })
          .then(() => {
            this.loading = false
          })
      },
      doSearch(searchForm) {
        searchForm = (!(searchForm instanceof MouseEvent) && searchForm) || this.searchForm
        this.loading = true
        this.$store
          .dispatch('getMedicationList', {
            id: this.searchForm.id,
            paramName: 'patient',
            value: this.searchForm.patientName,
            type: this.type
          })
          .then(() => {
            console.log('res')
            this.loading = false
          })
      },
      create() {
        this.editData = {
          appointmentId: '123',
          serviceTypeCode: '397',
          serviceTypeName: '普通门诊',
          appointmentTypeCode: '1',
          appointmentTypeName: '复诊',
          startTime: '2019-07-02 10:30:00',
          endTime: '2019-07-02 11:00:00',
          patientId: localStorage.getItem('patientId'),
          patientName: '张三',
          visitDoctorName: '李四',
          visitDeptName: '眼科门诊'
        }
        this.isUpdate = false
        this.dialogOpen = true
      },
      onCreate(row) {
        this.syncDataReady = false
        ajax
          .post('/appointment', JSON.stringify(row), {headers: {'Content-Type': 'application/json'}})
          .then(res => {
            this.syncDataReady = true
            this.searchForm.id = res.data.myId.myUnqualifiedId
            this.doSearch()
            window.setTimeout(() => {
              this.dialogOpen = false
              this.$Message.success(`新增${this.title}成功`)
            }, 200)
          })
          .catch(err => {
            this.syncDataReady = true
            this.$Message.error(err.message)
          })
      },
      update(row) {
        this.editData = row
        this.dialogOpen = true
        this.isUpdate = true
      },
      onUpdate(row) {
        this.syncDataReady = false
        ajax
          .put('/appointment/' + row.id, JSON.stringify(row), {headers: {'Content-Type': 'application/json'}})
          .then(res => {
            this.syncDataReady = true
            this.doSearch()
            window.setTimeout(() => {
              this.dialogOpen = false
              this.$Message.success(`更新${this.title}成功`)
            }, 200)
          })
          .catch(() => {
            this.syncDataReady = true
          })
      },
      remove(row) {
        this.$Modal.confirm({
          title: '删除确认',
          content: '<p>是否确认删除当前数据?</p>',
          onOk: () => {
            this.pageLoading = true
            this.$store
              .dispatch('deleteMedication', Object.assign(row, {type: this.type}))
              .then(() => {
                this.pageLoading = false
                this.$Message.success('删除成功')
                this.searchForm = {id:row.id}
                this.doSearch()
              })
              .catch(() => {
                this.pageLoading = false
              })
          },
          onCancel: () => {
          }
        })
      },
      pageChange(pageNo) {
        this.pageNo = pageNo
        this.doSearch()
      },
      pageSizeChange(pageSize) {
        this.pageSize = pageSize
        this.doSearch()
      },
      getPatient(data, key) {
        if (data && data.length) {
          let res = ''
          data.some(item => {
            if (item.actor) {
              res = item.actor[key] && item.actor[key] ? item.actor[key].myStringValue : ''
              return true
            }
            return false
          })
          return res
        } else {
          return ''
        }
      },
      formatDate(date, format) {
        if (!date) {
          console.error('formatDate函数date参数不可为空!')
          return ''
        }

        if (format === 'yyyy-mm-dd hh:mm:ss') {
          date = date instanceof Date || new Date(date)
          let years = date.getFullYear()
          let month = this.addZero(date.getMonth() + 1)
          let days = this.addZero(date.getDate())
          let hours = date.getHours()
          let min = date.getMinutes()
          let sec = date.getSeconds()

          return `${years}-${month}-${days} ${hours}:${min}:${sec}`
        }
      },
      addZero(temp) {
        if (temp < 10) return '0' + temp
        else return temp
      }
    }
  }
</script>

<style lang="less" scoped>
</style>
